local oo = require 'loop.base'

dofile(os.getenv('LUAR_HOME') .. '/core/Core.lua')

ApplicationProcessor = oo.class{}

function ApplicationProcessor:processApplication( code )
	
	local oldcode = code
	

	local i1, j1 = string.find( code, '<%%!' )
	
	while i1 do
		local i2, j2 = string.find( code, '%%>', j1+1 )
		if i2 == nil then
			print( 'Error: Unmatched tag <%!' )
			return nil
		end
		
		left = string.sub( code, 1, j1-3 ) 
		right = string.sub( code, j2+1, #code)
		
		code = left .. right
		
		i1, j1 = string.find( code, '<%%!', 1 )
	end

	i1, j1 = string.find( code, '<%%' )
	
	while i1 do
		
		local i2, j2 = string.find( code, '%%>', j1+1 )
		if i2 == nil then
			print( 'Error: Unmatched tag <%' )
			return nil
		end
		
		local str = string.sub( code, j1+1, i2-1 )
		str = string.gsub( str, "includeComponent", "ncl_trees[#ncl_trees+1] = includeComponent" )

		str = string.gsub( str, "print", "ret = ret .. " )
		str = 'local ret = ""' .. str .. 'return ret'
	
		local f = assert(loadstring( str ))
		
		str = f()

		left = string.sub( code, 1, j1-2 ) 
		right = string.sub( code, j2+1, #code)
		
		code = left .. str .. right
		
		i1, j1 = string.find( code, '<%%', 1 )
	end
	
	return code
	
end

function ApplicationProcessor:processTemplate( code )
	
	local i1, j1 = string.find( code, '<%%' )

	local i2, j2 = string.find( code, '%%>', j1+1 )

	local str = string.sub( code, j1+1, i2-1 )
	str = string.gsub( str, "includeTemplate", "return includeTemplate" )
	
	local f = assert( loadstring( str ) )
	
	str = f()
	
	return str
	
end
